package com.jxc.action.qxgl;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VUser;
import com.jxc.service.UserServiceI;
import com.jxc.util.IpUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/")
@Action(value = "loginAction", results = {
		@Result(name = "login", location = "/login.jsp"),
		@Result(name = "logout", location = "/index.html", type = "redirect"),
		@Result(name = "index", location = "/index.html", type = "redirect") })
public class LoginAction extends BaseAction implements ModelDriven<VUser> {

	private final static Logger logger = Logger.getLogger(LoginAction.class);

	private VUser vUser = new VUser();

	@Autowired
	private UserServiceI userService;

	public String login() {
		VUser u = userService.login(vUser);
		if (u != null) {
			SessionInfo sessionInfo = new SessionInfo();
			sessionInfo.setUserId(u.getId());
			sessionInfo.setLoginName(u.getUsername());
			sessionInfo.setLoginPassword(u.getPassword());
			sessionInfo.setIp(IpUtil.getIpAddr(ServletActionContext
					.getRequest()));
			ServletActionContext.getRequest().getSession().setAttribute(
					ResourceUtil.getSessionInfoName(), sessionInfo);
			sessionInfo.setAuthIds(u.getAuthIds());
			sessionInfo.setAuthNames(u.getAuthNames());
			sessionInfo.setRoleIds(String.valueOf(u.getRoid()));
			sessionInfo.setRoleNames(u.getRoname());
			sessionInfo.setAuthUrls(u.getAuthUrls());
			sessionInfo.setRepertoryIds(String.valueOf(u.getReid()));
			sessionInfo.setType(u.getUserType());
			logger.info("登录成功！");
		} else {
			logger.info("登录失败！");
			return "login";
		}
		return "index";
	}

	public String logout() {
		ServletActionContext.getRequest().getSession().invalidate();
		logger.info("登出成功！");
		return "logout";
	}

	@Override
	public VUser getModel() {
		return vUser;
	}
}
